package socket02_;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @description:
 * @Author yyp
 * @time 2022/3/31
 */
public class SocketTCPClient02 {
    public static void main(String[] args)  throws IOException {
        //思路
        // 1. 连接服务端 (ip , 端口）
        // 解读: 连接本机的 9999 端口, 如果连接成功，返回 Socket 对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端 socket返回="+socket.getClass());
        //2. 连接上后，生成 Socket, 通过 socket.getOutputStream()
        // 得到 和 socket 对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();
        //3. 通过输出流，写入数据到 数据通道
        outputStream.write("hello server".getBytes());
        // 设置结束标记
        //socket.shutdownOutput();

        InputStream inputStream = socket.getInputStream();
        byte[] read = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(read))!=-1){
            System.out.println(new String(read,0,readLen));
        }

        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端推出");
    }
}
